import axios from 'axios'
import { defineStore } from 'pinia'

export const useDockerContainerStore = defineStore('dockerContainer', {
  state: () => ({
    containers: [] as any[],
    loading: false,
    error: null as string | null,
  }),
  actions: {
    setContainers(list: any[]) {
      this.containers = list || []
    },
    setLoading(loading: boolean) {
      this.loading = loading
    },
    setError(error: string | null) {
      this.error = error
    },
    async fetchContainers() {
      this.setLoading(true)
      this.setError(null)
      try {
        const response = await axios.get('/api/docker/getAllContainers', { timeout: 5000 })
        if (response.status == 200) {
          this.setContainers(response.data)
          return true
        } else {
          throw new Error(`Error fetching containers: ${response.statusText}`)
        }
      } catch (err: any) {
        this.setError(err.message || 'Failed to fetch Docker containers')
        return false
      } finally {
        this.setLoading(false)
      }
    },
    clear() {
      this.containers = []
    },
  },
  getters: {
    containersIsEmpty: (state) => state.containers.length === 0,
  },
})
